<template>
  <el-container class="order-container">
    <el-main>
      <el-row>
        <el-col :span="6">
          <h3>已购买课程 <span style="color: #F56C6C">{{effectiveOrderCount}}</span> 单</h3>
        </el-col>
        <el-col :span="10">
          <h3>累计购课金额 <span style="color: #F56C6C">¥ {{actualIncomeAmount||0.00}}</span></h3>
        </el-col>
        <el-col :span="8" class="tx-r">
          <el-button size="medium" type="primary" @click="handleChangeRange" :disabled="changeRangeAbled">修改课程范围
          </el-button>
          <el-button size="medium" type="primary" @click="viewRecords">课程范围修改记录</el-button>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <table-view
          :templateDiv="{operation:true,orderStatus:true,courseRange:true,payAmount:true}"
          :columns="tableContent"
          :pageList="courseOrderList">
          <template slot="payAmount" slot-scope="scope">
            ￥{{scope.row.payAmount}}
          </template>
          <template slot="orderStatus" slot-scope="scope">
            {{scope.row.orderStatus | orderStatusFilter}}
          </template>
          <template slot="operation" slot-scope="scope">
            <el-button size="mini">
              <router-link :to="{name:'orderDetail',query:{id:scope.row.orderId}}">查看订单</router-link>
            </el-button>
          </template>
          <template slot="courseRange" slot-scope="scope">
            {{scope.row.hasOwnProperty('giftMonthAge')? scope.row.giftMonthAge : scope.row.startMonthAge}}-
            {{scope.row.endMonthAge}}
          </template>
        </table-view>

        <!--分页-->
        <pagination-view  :pagesize="pageInfo.pageSize"
          :currentPage="pageInfo.pageNumber"
          :total="total"
          @size-change="sizeChange"
          @current-change="pageChange"
        ></pagination-view>
      </el-row>
    </el-main>
    <el-footer></el-footer>

    <el-dialog title="修改课程范围" :visible.sync="dialogChangeVisible" width="50%" :destroy-on-close="true">
      <el-form ref="form" :model="form" :rules="rule" label-width="150" style="width: 85%">

        <el-form-item label="当前课程范围：">
          {{form.hasOwnProperty('giftMonthAge')? form.giftMonthAge : form.startMonthAge}}-
          {{form.endMonthAge}}
        </el-form-item>
        <el-form-item label="可修改范围月数：">
          {{form.noSendCount}}个月
        </el-form-item>
        <el-form-item prop="targetSalerId" label="修改课程范围:">
          <el-row :gutter="10" class="item-wrap">
            <el-col :span="2" v-for="(item,i) in monthAgeList" :key="i">
             <span :class="handleClassName(item)" @click="!item.hasSend&&!item.disabled&&selectStart(item.value)">
               {{item.value}}
             </span>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item prop="memo" label="修改说明：:">
          <el-input v-model.trim="form.memo" type="textarea" placeholder="请填写修改说明"></el-input>
        </el-form-item>
        <el-form-item class="tx-c">
          <el-button type="primary" @click="onSubmit">提交</el-button>
          <el-button @click="dialogChangeVisible=false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-dialog title="课程范围修改记录" :visible.sync="dialogRecordsVisible" width="50%" :destroy-on-close="true">
      <table-view
        :columns="recordsTableContent"
        :pageList="recordsList">
      </table-view>
    </el-dialog>
  </el-container>
</template>

<script>
  import TableView from '@/components/TableView'
  import PaginationView from '@/components/PaginationView'

  import * as pageApi from '@/api/user/userManage'

  import orderApi from '@/api/order/courseOrder/orderList'


  export default {
    name: 'CourseOrderInfo',
    components: {
      TableView, PaginationView
    },
    props: {
      active: {
        type: String
      }
    },
    computed: {},
    data() {
      return {
        id: '',
        changeRangeAbled:true,
        actualIncomeAmount: '',
        effectiveOrderCount: '',
        courseOrderList: [],
        dialogRecordsVisible: false,
        dialogChangeVisible: false,
        monthAgeListInit: this.$const.MONTH_OPTION(35),
        monthAgeHandleInit: [],
        monthAgeList: [],
        dialogType: '',
        pageInfo: {
          pageNum: 1,
          pageSize: 20,
          userId: ''
        },
        total: 0,
        recordsTableContent: [{
          field: 'preBusBabyBirth',
          label: '修改前生日'
        }, {
          field: 'busBabyBirth',
          label: '修改后生日'
        }, {
          field: 'createUsername',
          label: '修改人'
        }, {
          field: 'updateTime',
          label: '提交时间'
        }, {
          field: 'memo',
          label: '备注'
        }
        ],
        recordsList: [],
        tableContent: [{
          field: 'orderNo',
          label: '订单编号',
        }, {
          field: 'productTypeName',
          label: '课程名称'
        }, {
          field: 'productName',
          label: '规格'
        }, {
          field: 'courseRange',
          label: '课程范围'
        }, {
          field: 'payAmount',
          label: '实付金额'
        }, {
          field: 'createTime',
          label: '购买时间',
        }, {
          field: 'orderLearnEndTime',
          label: '到期时间',
        }, {
          field: 'orderStatus',
          label: '订单状态'
        }, {
          field: 'operation',
          width: '250px',
          label: '操作'
        }],
        form: {
          hasSendMonthAgeList: [],
          memo: ''
        },
        rule: {
          memo: [{ required: true, trigger: 'blur', message: '请填写修改说明' }]
        },
        shouldSelectArr: []

      }
    },
    filters: {
      orderStatusFilter(val) {
        return {
          0: '待付款',
          1: '学习中',
          2: '已完成',
          3: '已关闭',
          4: '退款'
        }[val]
      }
    },
    watch: {
      active: {
        handler(val) {
          if (val === 'courseOrder') {
            let { id } = this.$route.query
            this.id = id
            this.pageInfo.userId = id
            this.getData()
            this.getOrderCount().then(()=>{
              this.getOrderBirthUpdateRecordByUserId()
            })

          }
        },
        immediate: true
      }
    },
    methods: {
      handleClassName(item) {
        return item.hasSend ? 'one-item hasSend' : item.selected ? 'one-item selected' : item.disabled ? 'one-item disabled' : 'one-item'
      },
      computeSelectArr(start, hasSendArr, noSendCount) {
        let select = start
        let shoudSelectArr = []
        for (let i = 0; i < noSendCount; i++) {
          if (select < 36) shoudSelectArr.push(select)
          let plused = select += 1
          hasSendArr.map(item => {
            if (plused === item) {
              plused++
              select = plused
            } else {
              select = plused
            }
          })
        }
        return shoudSelectArr
      },
      selectStart(selected) {
        this.monthAgeList = JSON.parse(JSON.stringify(this.monthAgeHandleInit))
        let noSendCount = this.form.noSendCount
        this.shouldSelectArr = this.computeSelectArr(selected, this.form.hasSendMonthAgeList, noSendCount)
        if (this.shouldSelectArr.length < noSendCount) {
          this.$message.warning('选择修改范围不足，请重新选择')
        }
        this.monthAgeList.map(item => {
          delete item.selected
          this.shouldSelectArr.map(one => {
            if (one === item.value && !item.hasSend) {
              item['selected'] = true
            }
          })
        })
      },
      getOrderBirthUpdateRecordByUserId() {
        pageApi.getOrderBirthUpdateRecordByUserId(this.id).then(res => {
          this.recordsList = res.body
          this.changeRangeAbled = this.recordsList.length||!this.courseOrderList.length?true:false
        })
      },
      viewRecords() {
        this.dialogRecordsVisible = true
      },
      handleChangeRange() {
        this.getUpdatePrepareInfo(this.id)
        this.dialogChangeVisible = true
      },
      getUpdatePrepareInfo(id) {
        pageApi.getUpdatePrepareInfo(id).then(res => {
          this.form = res.body
          this.form.hasSendMonthAgeList=res.body.hasSendMonthAgeList || []
          this.form.userId = id
          this.monthAgeList = this.monthAgeListInit
          let noSendCount = this.form.noSendCount
          this.monthAgeList.map(item => {
            this.form.hasSendMonthAgeList.map(one => {
              if (item.value === one) {
                item['hasSend'] = true
              } else if (item.value < (Math.min(...this.form.hasSendMonthAgeList) - noSendCount)) {
                item['disabled'] = true
              }
            })
          })
          this.shouldSelectArr = []
          this.monthAgeHandleInit = JSON.parse(JSON.stringify(this.monthAgeList))
        })
      },

      onSubmit() {
        let _this = this
        _this.$refs['form'].validate((valid) => {
          if (valid) {
            if (!this.shouldSelectArr.length) {
              return this.$message.warning('请选择修改的课程范围')
            } else if (this.shouldSelectArr.length < this.form.noSendCount) {
              return this.$message.warning('选择月龄不足，请重新选择')
            }
            let postData = Object.assign({}, this.form)
            postData.startMonthAgeForUpdate = this.shouldSelectArr[0]
            postData.endMonthAgeForUpdate = this.shouldSelectArr[this.shouldSelectArr.length - 1]
            let hasSendMonthAgeList = this.form.hasSendMonthAgeList
            let start =  hasSendMonthAgeList.length?(hasSendMonthAgeList[hasSendMonthAgeList.length - 1]+1):this.form.startMonthAge
            postData.offset = this.shouldSelectArr[0] - start
            pageApi.updateOrderMonthAge(postData).then(res => {
              this.handleMessage(res)
              if (res.code === '200') {
                this.dialogChangeVisible = false
                this.getData()
                this.getOrderBirthUpdateRecordByUserId()
              }
            })
          }
        })
      },
      // pageSize变化函数
      sizeChange(val) {
        this.pageInfo.pageSize = val
        this.getData()
      },
      // page变化函数
      pageChange(val) {
        this.pageInfo.pageNumber = val
        this.getData()
      },
      getOrderCount() {
        return new Promise((resolve,reject) =>{
          pageApi.getCourseOrderCountByUserId(this.id).then(res => {
            let data = res.body
            this.actualIncomeAmount = data.actualIncomeAmount
            this.effectiveOrderCount = data.effectiveOrderCount
            resolve(true)
          })
        })
      },
      getData() {
        orderApi.getList(this.pageInfo).then(res => {
          this.courseOrderList = res.body.records
          this.total = Number(res.body.total)
          this.pageInfo.pageNumber = Number(res.body.pageNumber) || 1
        })
      }

    },
    mounted() {

    }
  }
</script>

<style lang="scss" scoped>
  .item-wrap {
    clear: both;
    padding-left: 30px
  }

  .one-item {
    display: inline-block;
    border: 1px solid #ddd;
    border-radius: 50%;
    text-align: center;
    height: 40px;
    width: 40px;
    line-height: 40px;
    margin-top: 5px;
    cursor: pointer;
    pointer-events: auto;
  }

  .disabled {
    background: #ddd;
    color: #fff;
    cursor: not-allowed;
  }

  .hasSend {
    background: #8c939d;
    color: #fff;
    cursor: not-allowed;
  }

  .selected {
    background: #409EFF;
    color: #fff;
  }

  .order-container {
    font-pageSize: 13px;
  }

  h4 {
    border-left: 1px solid #666;
    padding-left: 8px;
  }

  p {
    padding-left: 15px;
  }

  .order-statue {
    background: #ddd;
    padding: 8px;
  }

  .bottom-line {
    clear: both;
    border-bottom: 2px solid #666;
    padding-bottom: 10px;
    /*padding-top: 10px;*/
  }
</style>
